package com.allenlee.mvphelper.manager;

import android.content.Context;
import android.content.SharedPreferences;

import com.allenlee.mvphelper.MHApplication;
import com.allenlee.mvphelper.module.login.Account;
import com.allenlee.mvphelper.util.encryption.AESHelper;

/**
 * @author : lifei
 * 创建时间： 19-12-17
 * 更改时间： 19-12-17
 * Email : allen.lee723@qq.com
 * @version :
 * Description：
 */
public class PreferencesManager {

    private static final String SP_DEFAULT = "sp_default";

    private static final String KEY_CLIENT_ID = "key_client_id";
    private static final String KEY_PASSWORD = "key_password";
    private static final String KEY_SAVE_ACCOUNT = "key_save_account";

    private SharedPreferences sharedPreferences;

    private PreferencesManager() {
        sharedPreferences = MHApplication.getContext().getSharedPreferences(SP_DEFAULT, Context.MODE_PRIVATE);
    }

    /**
     * 单例持有者
     */
    private static class SingletonHolder {
        private static final PreferencesManager INSTANCE = new PreferencesManager();
    }

    public static PreferencesManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 保存账户信息
     * @param account 账户信息
     */
    public void saveAccount(Account account) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (account.isSaved()) {
            editor.putString(KEY_CLIENT_ID, AESHelper.encrypt(account.getClientId()));
            editor.putString(KEY_PASSWORD, AESHelper.encrypt(account.getPassword()));
        } else {
            editor.remove(KEY_CLIENT_ID);
            editor.remove(KEY_PASSWORD);
        }
        editor.putBoolean(KEY_SAVE_ACCOUNT, account.isSaved());
        editor.apply();
    }

    /**
     * 获取账户信息
     * @return 账户信息
     */
    public Account getAccount() {
        String clientId = AESHelper.decrypt(sharedPreferences.getString(KEY_CLIENT_ID, ""));
        String password = AESHelper.decrypt(sharedPreferences.getString(KEY_PASSWORD, ""));
        boolean isSaved = sharedPreferences.getBoolean(KEY_SAVE_ACCOUNT, false);
        return new Account(clientId, password, isSaved);
    }
}